package com.southminority.ethnic.controller.admin.contact;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.service.contact.ContactInfoService;
import com.southminority.ethnic.controller.contact.vo.ContactInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 联系信息管理端控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "🛠️ 联系信息管理后台", description = "管理员维护实验室公开联系方式的后台接口")
@RestController
@RequestMapping("/admin/contact-info")
@CrossOrigin
public class ContactInfoAdminController {

    private final ContactInfoService contactInfoService;

    public ContactInfoAdminController(ContactInfoService contactInfoService) {
        this.contactInfoService = contactInfoService;
    }

    /**
     * 分页查询联系信息列表
     */
    @GetMapping("/page")
    @Operation(
        summary = "分页查询联系信息列表",
        description = "管理员分页查询联系信息，支持按关键词、类型、状态筛选"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = PageResult.class))),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<PageResult<ContactInfoVO>> getContactInfoPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "搜索关键词，支持标题、内容搜索", example = "实验室") @RequestParam(required = false) String keyword,
            @Parameter(description = "类型筛选", example = "phone",
                schema = @Schema(allowableValues = {"address", "phone", "email", "website", "social"})) 
            @RequestParam(required = false) String type,
            @Parameter(description = "状态筛选", example = "1",
                schema = @Schema(allowableValues = {"1", "0", "-1"})) 
            @RequestParam(required = false) Integer status) {
        try {
            PageResult<ContactInfoVO> pageResult = contactInfoService.getContactInfoPage(current, size, keyword, type, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询联系信息失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有联系信息列表
     */
    @GetMapping("/list")
    @Operation(
        summary = "获取所有联系信息列表",
        description = "管理员获取所有联系信息的完整列表，不分页"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(type = "array", implementation = ContactInfoVO.class))),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<List<ContactInfoVO>> getAllContactInfoList() {
        try {
            List<ContactInfoVO> contactInfoList = contactInfoService.getAllContactInfoList();
            return R.ok(contactInfoList);
        } catch (Exception e) {
            log.error("获取所有联系信息列表失败", e);
            return R.fail("获取列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取联系信息详情
     */
    @GetMapping("/detail/{id}")
    @Operation(
        summary = "获取联系信息详情",
        description = "管理员根据ID获取特定联系信息的详细内容"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功",
            content = @Content(schema = @Schema(implementation = ContactInfoVO.class))),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<ContactInfoVO> getContactInfoById(@Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id) {
        try {
            ContactInfoVO contactInfo = contactInfoService.getContactInfoById(id);
            return R.ok(contactInfo);
        } catch (Exception e) {
            log.error("获取联系信息详情失败: id={}", id, e);
            return R.fail("获取详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建联系信息
     */
    @PostMapping("/create")
    @Operation(
        summary = "创建联系信息",
        description = "管理员新增一条联系信息，如新的办公地址、联系电话等"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = ContactInfoVO.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<ContactInfoVO> createContactInfo(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "新的联系信息数据",
                required = true,
                content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = ContactInfoVO.class),
                    examples = @ExampleObject(
                        name = "创建联系电话示例",
                        value = """
                        {
                          "type": "phone",
                          "title": "项目合作咨询电话",
                          "icon": "fas fa-handshake",
                          "contentList": ["王经理: 13987654321"],
                          "description": "专项用于项目合作咨询",
                          "isPublic": true,
                          "displayOrder": 10
                        }
                        """
                    )
                )
            )
            @RequestBody ContactInfoVO contactInfoVO) {
        try {
            log.info("管理员创建联系信息: 标题={}, 类型={}", contactInfoVO.getTitle(), contactInfoVO.getType());
            ContactInfoVO result = contactInfoService.createContactInfo(contactInfoVO);
            return R.ok(result);
        } catch (Exception e) {
            log.error("创建联系信息失败", e);
            return R.fail("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新联系信息
     */
    @PutMapping("/update/{id}")
    @Operation(
        summary = "更新联系信息",
        description = "管理员更新指定ID的联系信息"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = ContactInfoVO.class))),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<ContactInfoVO> updateContactInfo(
            @Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "要更新的联系信息数据",
                required = true,
                content = @Content(schema = @Schema(implementation = ContactInfoVO.class))
            )
            @RequestBody ContactInfoVO contactInfoVO) {
        try {
            log.info("管理员更新联系信息: ID={}, 标题={}", id, contactInfoVO.getTitle());
            ContactInfoVO result = contactInfoService.updateContactInfo(id, contactInfoVO);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新联系信息失败: id={}", id, e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除联系信息
     */
    @DeleteMapping("/delete/{id}")
    @Operation(
        summary = "删除联系信息",
        description = "管理员软删除指定的联系信息"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "删除成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> deleteContactInfo(@Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id) {
        try {
            log.info("管理员删除联系信息: ID={}", id);
            Boolean result = contactInfoService.deleteContactInfo(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除联系信息失败: id={}", id, e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除联系信息
     */
    @DeleteMapping("/batch-delete")
    @Operation(
        summary = "批量删除联系信息",
        description = "管理员批量软删除联系信息"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "批量删除成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "400", description = "ID列表不能为空"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> batchDeleteContactInfo(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "要删除的联系信息ID列表",
                required = true,
                content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(type = "array", implementation = Long.class),
                    examples = @ExampleObject(value = "[1, 2, 3]")
                )
            )
            @RequestBody List<Long> ids) {
        try {
            log.info("管理员批量删除联系信息: IDs={}", ids);
            Boolean result = contactInfoService.batchDeleteContactInfo(ids);
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量删除联系信息失败", e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 更新联系信息状态
     */
    @PutMapping("/status/{id}")
    @Operation(
        summary = "更新联系信息状态",
        description = "管理员更新联系信息的状态，如启用、禁用"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = Boolean.class))),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "400", description = "状态参数无效"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> updateContactInfoStatus(
            @Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id,
            @Parameter(description = "新状态：1-启用，0-禁用", example = "0", required = true,
                schema = @Schema(allowableValues = {"1", "0"})) 
            @RequestParam Integer status) {
        try {
            log.info("管理员更新联系信息状态: ID={}, Status={}", id, status);
            Boolean result = contactInfoService.updateContactInfoStatus(id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新联系信息状态失败: id={}, status={}", id, status, e);
            return R.fail("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 设置主要联系方式
     */
    @PutMapping("/primary/{id}")
    @Operation(
        summary = "设置主要联系方式",
        description = "管理员设置或取消某条联系信息为主要联系方式"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "设置成功"),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> setPrimaryContactInfo(
            @Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id,
            @Parameter(description = "是否主要：1-是，0-否", example = "1", required = true,
                schema = @Schema(allowableValues = {"1", "0"})) 
            @RequestParam Integer isPrimary) {
        try {
            log.info("管理员设置主要联系方式: ID={}, IsPrimary={}", id, isPrimary);
            Boolean result = contactInfoService.setPrimaryContactInfo(id, isPrimary);
            return R.ok(result);
        } catch (Exception e) {
            log.error("设置主要联系方式失败: id={}, isPrimary={}", id, isPrimary, e);
            return R.fail("设置失败: " + e.getMessage());
        }
    }

    /**
     * 设置公开显示
     */
    @PutMapping("/public/{id}")
    @Operation(
        summary = "设置公开显示",
        description = "管理员设置某条联系信息是否在前端公开显示"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "设置成功"),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> setPublicContactInfo(
            @Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id,
            @Parameter(description = "是否公开：1-是，0-否", example = "0", required = true,
                schema = @Schema(allowableValues = {"1", "0"})) 
            @RequestParam Integer isPublic) {
        try {
            log.info("管理员设置公开显示: ID={}, IsPublic={}", id, isPublic);
            Boolean result = contactInfoService.setPublicContactInfo(id, isPublic);
            return R.ok(result);
        } catch (Exception e) {
            log.error("设置公开显示失败: id={}, isPublic={}", id, isPublic, e);
            return R.fail("设置失败: " + e.getMessage());
        }
    }

    /**
     * 更新显示顺序
     */
    @PutMapping("/order/{id}")
    @Operation(
        summary = "更新显示顺序",
        description = "管理员调整联系信息的显示顺序"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "404", description = "联系信息不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Boolean> updateDisplayOrder(
            @Parameter(description = "联系信息ID", example = "1", required = true) @PathVariable Long id,
            @Parameter(description = "显示顺序，数字越小越靠前", example = "1", required = true,
                schema = @Schema(minimum = "0")) 
            @RequestParam Integer displayOrder) {
        try {
            log.info("管理员更新显示顺序: ID={}, DisplayOrder={}", id, displayOrder);
            Boolean result = contactInfoService.updateDisplayOrder(id, displayOrder);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新显示顺序失败: id={}, displayOrder={}", id, displayOrder, e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    @Operation(summary = "测试接口连通性")
    @ApiResponse(responseCode = "200", description = "服务正常")
    public R<String> test() {
        return R.ok("联系信息管理后台服务正常");
    }
} 
